﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.IO;

using RHFrameWork;

namespace ResumeHelper
{
    public class WebSiteProcessWorker
    {
        public static WebSiteProcessInfos WSProcessInfos = new WebSiteProcessInfos();
        public static Dictionary<string, WebSiteProcess> WBPProcessList = new Dictionary<string, WebSiteProcess>();

        public static UserInfo User = new UserInfo();

        public static bool InitUser(string uid,string pwd)
        {
            try
            {
                string str = WebHelper.SendPostRequest(PublicObject.WEBURL_USERINFO, "eMail=" + uid + "&pwd=" + pwd);

                if (str.Trim().ToUpper().Equals("NG") == true)
                {
                    return false;
                }

                User.Load(str);
                return true;
            }
            catch 
            {
                return false;
            }
        }

        public static int InitWBPNameList()
        {
            int rst = -1;
            try
            {
                string str = WebHelper.SendPostRequest(PublicObject.WEBURL_WEB_SITE_PROCESS_LIST, "");

                WSProcessInfos.Load(str);
                rst = WSProcessInfos.Count;
                return rst;
            }
            catch
            {
                return rst;
            }
        }

        public static void LoadWebSiteProcess(string HostName)
        {
            Assembly assem = null;
            
            try
            {
                string strData = WebHelper.SendPostRequest(PublicObject.WEBURL_WEB_SITE_PROCESS, "host=" + HostName);
                Byte[] ary = Convert.FromBase64String(strData);

                string strPath = System.Windows.Forms.Application.StartupPath + @"\temp.dll";
                File.WriteAllBytes(strPath, ary);
                
                //assem = Assembly.LoadFrom(@"D:\SVN\ResumeHelper\" + HostName + @"\bin\Debug\" + HostName + ".dll");
                assem = Assembly.LoadFrom(strPath);
                WebSiteProcess wbp = new WebSiteProcess(assem);

                WBPProcessList.Add(HostName, wbp);
            }
            catch (Exception err)
            {

                Console.WriteLine(err.Message);
            }
            
            
        }

        public static ProcessResult Process(WebBrowserXP browser,Uri url)
        {
            //if (WBPProcessList.ContainsKey(url.Host) == false)
            //{
            //    LoadWebSiteProcess(url.Host);
            //}
            
            if (WBPProcessList.ContainsKey(url.Host) == true)
            {
                return WBPProcessList[url.Host].Process(url, browser.Document, User);
            }

            return ProcessResult.Get(enumProcessResult.未处理, new object());
        }
    }
}
